package top.roadvast.rabbitmq.utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConnectionUtil {
    private static String host;

    private static int port;

    private static String username;

    private static String password;

    private static String vhost;

    private static Connection connection;

    static {
        host = "192.168.47.101";
        username = "roadvast";
        password = "123456";
        vhost = "/basic";
        port = 5672;
    }

    private ConnectionUtil() {

    }

    /**
     * 单例模式（双重检查锁）
     * 建立与RabbitMQ的连接
     * @return 连接对象
     * @throws IOException, TimeoutException
     */
    public static Connection getConnection() throws IOException, TimeoutException {
        if (connection == null) {
            synchronized (ConnectionUtil.class) {
                if (connection == null) {
                    //定义连接工厂
                    ConnectionFactory factory = new ConnectionFactory();
                    //设置服务地址
                    factory.setHost(host);
                    //端口
                    factory.setPort(port);
                    //设置账号信息，用户名、密码、vhost
                    factory.setVirtualHost(vhost);
                    factory.setUsername(username);
                    factory.setPassword(password);
                    // 通过工程获取连接
                    connection = factory.newConnection();
                }
            }
        }
        return connection;
    }
}